package com.atstudy.dao;

import com.atstudy.util.DateUtils;
import com.atstudy.pojo.Cla;
import com.atstudy.util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/1/11 15:01
 * @copyright: 博为峰
 */
public class ClaDaoImpl implements ClaDao {
    @Override
    public int insert(Cla cla) {
        Connection conn = DBUtils.getConn();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        int id = -1;
        try {
            //插入班级
            preparedStatement = conn.prepareStatement("insert into cla (name,num,create_time)values(?,?,?)");
            preparedStatement.setString(1, cla.getName());
            preparedStatement.setInt(2, cla.getNum());
            preparedStatement.setTimestamp(3, DateUtils.getTimestamp());
            System.out.println(preparedStatement);
            int i = preparedStatement.executeUpdate();
            preparedStatement = conn.prepareStatement("select last_insert_id()");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                id = resultSet.getInt(1);
            }
        } catch (SQLException throwables) {
            throw new RuntimeException("插入班级异常");
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return id;
    }

    @Override
    public int delete(int id) {
        return 0;
    }

    @Override
    public int update(Cla cla) {
        return 0;
    }

    @Override
    public ArrayList<Cla> select() {
        return null;
    }
}
